import 'reflect-metadata';
import { createConnection } from 'typeorm';
import { User } from '../entity/User';
import { Family } from '../entity/Family';
import { Line } from '../entity/Line';


let handlerRepository = async connection => {
  console.log('Inserting a new user into the database...');
  const user = new User();
  user.firstName = 'David';
  user.lastName = 'Lee';
  user.age = 25;
  // 使用Repository来代替manager操作
  let userRepository = connection.getRepository(User);
  await userRepository.save(user);
  console.log('user has been saved');

  let userList: Array<User> = await userRepository.find();
  console.log(userList);
  console.log('\n');

  let data1 = await userRepository.findOne(1);
  console.log('第一条数据是', data1);
  console.log('\n');

  data1.firstName = 'lisa';
  await userRepository.save(data1);
  console.log('已更新第一条数据');

  await userRepository.remove(data1);
  console.log('已删除第一条数据');

  // 找个一个具体的人
  let data2 = await userRepository.findOne({ lastName: 'Lee' });
  console.log('lastName is lee: ', data2);
  console.log('\n');

  // 找许多人
  let data3 = await userRepository.find({ firstName: 'David' });
  console.log(data3);
  console.log('\n');


  // 带有统计功能
  let [allUsers, usersCount] = await userRepository.findAndCount();
  console.log('All users: ', allUsers);
  console.log('Users count: ', usersCount);

  process.exit(0);
};

// 一对一
let handlerRepository2 = async connection => {
  console.log('Inserting a new user into the database...');
  const user = new User();
  user.firstName = 'ruyu';
  user.lastName = 'wang';
  user.age = 18;

  const family = new Family();
  family.address = 'Shanghai,minhang,qibao';
  family.info = 'very rich';
  family.num = 4;
  family.phone = '17621399151';
  family.user = user;

  let userRepository = connection.getRepository(User);
  await userRepository.save(user);
  console.log('user has been saved');

  let familyRepository = connection.getRepository(Family);
  await familyRepository.save(family);
  console.log('family save');
  process.exit(0);
};

let handlerRepository3 = async connection => {
  console.log('handlerRepository3');
  let userRepository = connection.getRepository(User);
  let users = await userRepository.find({ relations: ['family'] });
  console.log(users);
  process.exit(0);
};

let handlerRepository4 = async connection => {
  console.log('handlerRepository4');
  let userRepository = connection.getRepository(User);
  const user = new User();
  user.firstName = 'ruyu';
  user.lastName = 'wang';
  user.age = 16;
  await userRepository.save(user);
  console.log('user has been saved');

  const line = new Line();
  line.name = 'line1';
  line.users = [user];

  let lineRepository = connection.getRepository(Line);
  await lineRepository.save(line);
  console.log('line has been saved');
  process.exit(0);
};


createConnection().then(handlerRepository4).catch(error => console.log(error));
